import React, { useRef, useState } from 'react'
import {
  Dimensions,
  View,
  Text,
} from 'react-native'

import { WebView } from 'react-native-webview'
import { observer } from 'mobx-react-lite'

import { useStores } from '../stores'
import { Snackbar } from '../views'

export default observer(({ route, navigation }) => {
  const { bookApi, appearance: ap } = useStores()

  const [content, setContent] = useState()
  const [location, setLocation] = useState(0)

  const { type, _id } = route.params

  const ref = useRef()

  if (!content) {
    //nAJzYzAVB3ma
    bookApi.fetchAricle(_id).then(data => {
      const { content, name } = data.article

      const { sections } = content
      const html = `
      <html>
      <head>
      <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
      <style type="text/css">
      body {
        background: ${ap.theme.background};
        color: ${ap.theme.second};
        font-size: ${16}px;
        line-height: ${24}px;
        letter-spacing: 1px;
        padding: 32px 4px 24px 4px;
      }
      a {
        color: ${ap.theme.active}
      }
      div {
        text-indent: ${32}px;
        padding-bottom: ${8}px;
      }
      h1,h2,h3,h4,h5 {
        font-weight:normal;
      }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
      <script>
      $(document).ready(() => {
        $('a').each(function() {
          const raw  = $(this).attr('raw-href')
          if(raw.include('#')) {
            const [_, q] = raw.split('#')
            alert('#' + q)
            $(this).attr('href', '#' + q)
          }
        })
        $('a').click(event => {
          const href = $(event.target).attr('href')
          alert(href)
          if(href.include('#')) {
            return true
          }
          window.ReactNativeWebView.postMessage(href)
          event.preventDefault()
          return false
        })
      })
      </script>
      </head>
      <body>
      ${sections.join("")}
      </body>
      </html>
      `
      setContent(html)
    }).catch(err => {

      if (err.code === 1001) {
        alert(`文章丢了`)
        navigation.pop()
      }
      Snackbar.error({ text: err.toString() })
    })
    return <View style={{ ...styles.container }}><Text>Loading</Text></View>
  }

  const onMessage = event => {
    const [type, _id] = event.nativeEvent.data.split('://')
    if (type && _id)
      navigation.push('Reader', { type, _id })
  }
  return (
    <View
      style={{
        ...styles.container,
        backgroundColor: ap.theme.background
      }}
    >
      <WebView
        ref={ref}
        source={{ html: content }}
        style={{ ...styles.web, flex: 1 }}
        scrollEnabled={true}
        onMessage={onMessage}
        scrollIndicatorInsets={{ right: 1 }}
        onLayout={event => console.log(event.nativeEvent.layout.height)} />
    </View>

  )
})

const { width, height } = Dimensions.get("window")

const styles = {
  container: {
    flex: 1,
    position: 'absolute',
    width, height,
    left: 0,
    paddingTop: 0,
    paddingBottom: 0
  },

  web: {
    // paddingLeft: 24,
    // paddingRight: 24,
  }
}